//
//  ContactManager.m
//  OC04_集合(二)
//
//  Created by Hanlingyu on 16/7/7.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "ContactManager.h"

@implementation ContactManager
- (instancetype)initWithDictionary:(NSMutableDictionary *)dictionary {
    self = [super init];
    if (self) {
        _contactDictionary = dictionary;
    }
    return self;
}
// 添加联系人
- (void)addContact:(Contact *)contact {
    if (contact.name.length > 0 && contact.phoneNumber.length > 0) {
        NSLog(@"添加%@联系人成功", contact.name);
        NSMutableArray *contactArr = [_contactDictionary objectForKey:contact.groupName];
        if (contactArr == nil) {
            contactArr = [NSMutableArray arrayWithObject:contact];
            [_contactDictionary setObject:contactArr forKey:contact.groupName];
        } else {
            [contactArr addObject:contact];
        }
    } else {
        NSLog(@"添加%@联系人失败", contact.name);
    }
}

// 删除联系人
- (void)removeContact:(NSString *)contactName {
    NSString *firstChar = [contactName substringToIndex:1];
    NSMutableArray *contactArr = [_contactDictionary objectForKey:firstChar];
    BOOL isHave = NO;
    for (int i = 0; i < contactArr.count; i++) {
        Contact *contact = contactArr[i];
        if ([contact.name isEqualToString:contactName]) {
            [contactArr removeObjectAtIndex:i];
            [_contactDictionary setObject:contactName forKey:firstChar];
            isHave = YES;
            NSLog(@"删除后:%ld", contactArr.count);
        }
    }
    if (isHave == YES) {
        NSLog(@"联系人%@已经删除", contactName);
    } else {
        NSLog(@"联系人%@未找到", contactName);
    }
}
// 删除整组联系人
- (void)removeGroupWithGroupName:(NSString *)groupName {
    [_contactDictionary removeObjectForKey:groupName];
}

@end
